package com.tree;

public class Test2 {
    public static void main(String[] args) {
       int[] nums= new int[]{1, 2, 7, 4, 5, 2};
        System.out.println(getmax(nums, 0, nums.length));
    }
    //翻转二叉树
    public static TreeNode invertTree(TreeNode root) {

        if (root==null){
            return null;
        }
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }
    //将二叉树展开为链表
     public void flatten(TreeNode root){

        if (root==null){
            return;
        }
        //将左右子树拉伸成链表
        flatten(root.left);
        flatten(root.right);

         TreeNode left = root.left;
         TreeNode right = root.right;
         //左树为空，右变为左边
         root.left=null;
        root.right=left;
        TreeNode pump=root;
        while (pump.right!=null){
            pump= pump.right;
        }
        pump.right=right;
        
     }
     TreeNode build(int[] nums,int lo,int r){

        if (lo==r){
            return null;
        }
         int i = getmax(nums, lo, r);
         TreeNode root=new TreeNode(nums[i]);
         root.left=build(nums,lo,i-1);
         root.right=build(nums,i+1,r);
         return root;
     }
     public static int getmax(int[] nums,int l,int r){
        int index=l;
         for (int i = l; i < r; i++) {
             if (nums[i]>nums[index]){
                 index=i;
             }
         }
         return index;
     }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root==p){
    return p;
}
        if (root==q){
            return q;
        }
        if (p.val<root.val&&q.val<root.val){
            return lowestCommonAncestor(root.left,p,q);
        }else if (p.val>root.val&&q.val>root.val){
            return lowestCommonAncestor(root.right,p,q);
        }else {
            return root;
        }
    }

}
